;
(function(root, factory) {
    if (typeof define === "function" && define.amd) {
        define(["util", "listener", "baseTrack"], factory);
    } else {
        factory();
    }
})(this, function(util, listener, baseTrack) {
    this.legendofkage = this.legendofkage || {};
    if (util && listener) {
        this.legendofkage.Listener = listener;
        this.legendofkage.Util = util;
        this.legendofkage.BaseTrack = baseTrack;
    }

    function TrackListener() {
        TrackListener.__super__.constructor.apply(this, arguments);
        //系统预定义事件
        var evtType = {
            play: {
                value: null
            },
            stop: {
                value: null
            },
            pause: {
                value: null
            }
        };
        Object.assign(this.evtType, evtType);
    }
    legendofkage.Util.inherits(TrackListener, legendofkage.Listener);

    //重写unAll，防止预定义事件一并被清除
    TrackListener.prototype.unAll = function() {
        var keys = Object.keys(this.evtType);
        var frozeKeys = Object.keys(evtType);
        for (var i = 0, j = keys.length; i < j; i++) {
            this.evtType[keys[i]].length = 0;
            if (frozeKeys.indexOf(keys[i]) == -1)
                delete this.evtType[keys[i]];
            else
                this.evtType[keys[i]] = null;
        }
    }

    //播放状态
    var playState = {
        playing: "playing",
        pause: "pause",
        stop: "stop"
    }

    var instance, optSetting = {},
        tracks = {},
        activeTrack = null;

    //轨迹播放器,支持分段播放
    function TrackPlayer(opt) {
        TrackPlayer.__super__.constructor.apply(this, arguments);
        optSetting = (opt || {});
    };

    legendofkage.Util.inherits(TrackPlayer, TrackListener);

    var listenerPlayState = function(track) {
        var player = this;
        track.on(playState.stop, function(data) {
            /*只有轨迹在正常播放完毕后且播放器配置为自动播放下一轨迹时，才自动播放一下段轨迹
             当播放器停止某一正在播放的轨迹，则为非正常停止播放。换句话说，是停止了所有的轨迹播放，
             这时就不应该自动播放下一段轨迹了*/
            if (optSetting.autoPlayNext) {
                player.next();
            } else {
                player.dispatch("end", {
                    evtType: 'end',
                    target: player
                });
            }
        })
    }


    var isValidTrack = function(track) {
        return track && (typeof track instanceof legendofkage.BaseTrack || legendofkage.BaseTrack.prototype.isPrototypeOf(track));
    }

    //将轨迹添加到播放器
    //@track{Array|Object}
    TrackPlayer.prototype.addTrack = function(track) {
        var player = this;
        if (Array.isArray(track)) {
            track.forEach(function(item, index) {
                if (!isValidTrack(item)) {
                    throw new TypeError("轨迹只能是基于baseTrack的子类!");
                }
                tracks[item.getId()] = item;
                listenerPlayState.call(player, item);
            })
        } else if (isValidTrack(track)) {
            tracks[track.getId()] = track;
            listenerPlayState.call(player, track);
        }
    }

    //获取播放器中的某个轨迹
    //@return(Object|Array)
    TrackPlayer.prototype.getTrack = function(id) {
        if (id) {
            return tracks[id];
        }
        var returnValue = [];
        for (var item in tracks) {
            returnValue.push(tracks[item]);
        }
        return returnValue;
    }


    //获取即将播放或正在播放中的那个轨迹
    TrackPlayer.prototype.getActiveTrack = function() {
        if (activeTrack)
            return activeTrack;
        var keys = Object.keys(tracks);
        if (keys && keys.length >= 0) {
            return tracks[keys[0]];
        }
    }

    //获取播放器播放状态
    TrackPlayer.prototype.getState = function() {
        return activeTrack ? activeTrack.getState() : playState.stop;
    }

    //播放轨迹
    TrackPlayer.prototype.play = function(track) {
        track = track || this.getActiveTrack();
        if (track) {
            activeTrack = track;
            this.dispatch("start", {
                evtType: 'start',
                target: this,
                trackData: track.getTrackData()
            });
            track.run();
        }
    }

    //暂停播放
    TrackPlayer.prototype.pause = function() {
        if (activeTrack && activeTrack.getState() == playState.playing) {
            activeTrack.pause();
        }
    }

    //停止播放
    TrackPlayer.prototype.stop = function() {
        if (activeTrack && activeTrack.getState() == playState.playing) {
            activeTrack.stop();
        }
        this.clear();
    }

    //播放下一段轨迹
    TrackPlayer.prototype.next = function() {
        if (activeTrack && optSetting.autoPlayNext) {
            var keys = Object.keys(tracks);
            var index = keys.indexOf(activeTrack.getId().toString());
            if (index < keys.length - 1) {
                activeTrack.clearPersonMarker();
                this.play(this.getTrack(keys[index + 1]));
            } else {
                this.dispatch("end", {
                    evtType: 'end',
                    target: this
                });
            }
        }
    }

    //清除所有轨迹并销毁对象
    TrackPlayer.prototype.clear = function() {
            for (var item in tracks) {
                tracks[item].dispose();
                tracks[item] = null;
                delete tracks[item];
            }
            activeTrack = null;
            legendofkage.BaseTrack.resetId();
        }
        //设置播放速度
    TrackPlayer.prototype.setPlaySpeed = function(speed) {
        if (!isNaN(speed)) {
            for (var item in tracks) {
                tracks[item].setPlaySpeed(speed);
            }
        }
    }

    legendofkage.TrackPlayer = function(opt) {
        var optSetting = {
            autoPlayNext: true //前一段轨迹播放完成后是否自动播放下段轨迹
        };
        opt = opt || {};
        Object.assign(optSetting, opt);
        if (!instance) {
            instance = new TrackPlayer(optSetting);
        }
        return instance;
    }
    return legendofkage.TrackPlayer;
});